import axios from 'axios';
import qs from 'qs';
import common from '../utils/common.js'
import loadingService from '../components/loading/loadingService.js';
import alertService from '../components/alert/alertService.js';

const _base_url = '/';
function send(requestData,option,config) {
    let thisObj = this;
    let promise = new Promise((resolve, reject) => {
        let contentType = 'application/x-www-form-urlencoded';
        if(thisObj.useJson){
            contentType = 'application/json;charset=UTF-8';
        }
        let url = thisObj.url;
        if(thisObj.isRESTful){
            for(var i in requestData){
                url += '/' + requestData[i];
            }
        }
        if(thisObj.isRESTfulPost){
            for(var i in requestData){
                url += requestData[i];
            }
        }
        let headers = {
          'Content-type': contentType
        }
        if (sessionStorage.getItem('token')) {
          headers['TOKEN'] = sessionStorage.getItem('token')
        }
        let axiosOption = {
            method: 'post',
            baseURL: thisObj.baseURL ? thisObj.baseURL : _base_url,
            url: url,
            headers: headers,
            timeout: 3000,
            withCredentials: false,
        }

        let method = axiosOption.method;
        if(thisObj.method){
            method = thisObj.method.toLocaleLowerCase();
            axiosOption.method = method;
        }
        if(requestData){
            if(method == 'put' || method == 'post'){
                if(!thisObj.isRESTful){
                    if(thisObj.useJson){
                        axiosOption.data = JSON.stringify(requestData);
                    }
                    else{
                        axiosOption.data = qs.stringify(requestData,{allowDots: true});
                    }
                }
            }
            else{
                if(!thisObj.isRESTful){
                    axiosOption.params = requestData;
                }
            }
        }

        axiosOption = common.deepMerge(axiosOption, config);

        let loadingInstance = null;
        if(option && option.showLoading){
            loadingInstance = loadingService.create({loadingTxt:option.loadingTxt || '努力加载中，请耐心等候...'});
            loadingInstance.show();
        }

        axios(axiosOption).then(response=>{
            if(loadingInstance){
                loadingInstance.hide();
                loadingInstance.destroy();
            }

            if(response.status == 200){
                if(response.data && response.data.errCode == 900){
                    location.href = '#/login';
                }else{
                    if(response.data && !response.data.success && response.data.errMsg){
                        alertService.error(response.data.errMsg);
                    }
                    resolve(response.data);
                }
            }
            else{
                reject(error);
            }
        })
        .catch(error=>{
            if(loadingInstance){
                loadingInstance.hide();
                loadingInstance.destroy();
            }
            showCatchErrors(error)
            reject(error);
        })
    })

    return promise;
}

function showCatchErrors(error){
    let data = null;
    if(error.response){
        data = error.response.data;
    }else{
        data = error.message;
    }
    if(typeof data == 'string'){
        alertService.error(data);
        return;
    }

    let msg = '';
    if(data.errors){
        data.errors.forEach(item=>{
            msg += item.error + ": " + item.defaultMessage;
        })
    }
    if(!msg){
        msg =data.error + ": " +  data.message;
    }
    alertService.error(msg);
}

const apiService = {
    init: function (obj) {
        Object.keys(obj).forEach(item => {
            obj[item].send = send;
        })
        return obj;
    }
}
export default apiService;
